<template>
  <div class="App-flex">
    <AppCard>
      <!-- 搜索条件 -->
      <el-form v-show="showSearch" :inline="true">
        <el-form-item label="参数名称" prop="dictName">
          <el-input
            placeholder="请输入参数名称"
            v-model="searchParams.sys_name"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleListPage"
          ></el-input>
        </el-form-item>
        <el-form-item label="参数编号" prop="sys_type">
          <el-input
            placeholder="请输入参数编号"
            v-model="searchParams.id"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleListPage"
          ></el-input>
        </el-form-item>
        <el-form-item label="参数状态" prop="dictStatus">
          <el-select
            placeholder="请选择参数状态"
            v-model="searchParams.status"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleListPage"
          >
            <el-option label="启用" value="0" />
            <el-option label="停用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" plain v-debounce="handleSearch">搜索</el-button>
          <el-button type="danger" icon="refresh" plain v-throttle="resetSearch">重置</el-button>
          <el-button type="primary" icon="plus" plain @click="handleAdd()">新增</el-button>
        </el-form-item>
      </el-form>
      <div class="h-20px"></div>
      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        border
        :data="tableList"
        empty-text="暂时没有数据哟"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" prop="id" width="120px" align="center" type="index"></el-table-column>
        <el-table-column label="参数名称" prop="sys_name"  align="center"></el-table-column>
        <el-table-column label="参数值" prop="sys_value"  align="center"></el-table-column>
        <el-table-column label="参数类型" prop="sys_value" align="center"></el-table-column>
        <el-table-column label="参数状态" prop="status" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-text="启用"
              inactive-text="停用"
              :active-value="1"
              :inactive-value="2"
              :inline-prompt="true"
              @change="(val:string) => handleSwitch(scope.row, val)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="create_time"  align="center"></el-table-column>
        <el-table-column label="修改时间" prop="update_time"  align="center"></el-table-column>
        <el-table-column label="操作" align="center" width="120" fixed="right">
          <template #default="{ row }">
            <el-tooltip content="修改" placement="top">
              <el-button
                type="primary"
                icon="Edit"
                circle
                plain
                @click="handleUpdate(row)"
                v-auth="['system:role:update']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                type="danger"
                icon="Delete"
                circle
                plain
                @click="handleDelete(row)"
                v-auth="['system:role:delete']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <div class="h-20px"></div>
      <!-- {{ searchParams.pageNo }} --- {{ searchParams.pageSize }} -->
      <!-- 分页 -->
      <el-pagination
        background
        v-model:current-page="searchParams.page"
        v-model:page-size="searchParams.page_size"
        v-show="total > 0"
        :page-sizes="[10, 20, 50, 100, 200]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleListPage"
        @current-change="handleListPage"
      />

      <!-- 添加 OR 修改 -->
      <AppDrawer
        ref="AppDrawerRef"
        :title="title"
        @AppConfirm="handleConfirm"
        @AppCancel="handleCancel"
        :loading="confirmLoading"
      >
        <template #content>
          <el-form ref="formRef" :rules="rules" :model="form" label-width="80px" status-icon>
            <el-row>
              <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                <el-form-item label="参数名称" prop="sys_name">
                  <el-input v-model="form.sys_name" placeholder="请输入参数名称" clearable />
                </el-form-item>
                
                <el-form-item label="参数类型" prop="sys_type">
                  <el-input v-model="form.sys_type" placeholder="请输入参数类型" clearable />
                </el-form-item>

                <el-form-item label="参数值" prop="sys_type">
                  <el-input v-model="form.sys_value" placeholder="请输入参数类型" clearable />
                </el-form-item>
                
                <el-form-item label="参数状态" prop="status">
                  <el-select v-model="form.status" placeholder="请选择参数状态" clearable>
                    <el-option label="启用" :value="1" />
                    <el-option label="停用" :value="2" />
                  </el-select>
                </el-form-item>
                
                <el-form-item label="参数备注" prop="sys_explain">
                  <el-input v-model="form.sys_explain" :rows="5" type="textarea" placeholder="请输入参数备注" />
                </el-form-item>
              </el-col>
              
            </el-row>
          </el-form>
        </template>
      </AppDrawer>
    </AppCard>
  </div>
</template>

<script setup lang="ts" name="dictTypePage">
import { nextTick, ref, reactive, onMounted } from "vue";
import {
  AppNoticeSuccess,
  AppNoticeError,
  AppMsgError,
  AppMsgWarning,
  AppMsgBox
} from "@/utils/app.ts";
// @ts-ignore
import { listPage, getById, add, update, deleteById, updateStatus } from "@/api/system/dict/type/index.ts";

// 表格加载动画Loading
const loading = ref(false);
// 是否显示搜索表单[默认显示]
const showSearch = ref<boolean>(true); // 默认显示搜索条件
// 表格数据
const tableList = ref<any>([]);

// 查询参数
const searchParams = ref({
  page: 1, // 第几页
  page_size: 10, // 每页显示多少条
  id: "",
  sys_name: "",
  status: ""
});

const total = ref<number>(0);

/** 重置搜索参数 */
const resetSearchParams = () => {
  searchParams.value = {
  page: 1, // 第几页
  page_size: 10, // 每页显示多少条
  id: "",
  sys_name: "",
  status: ""
  };
};

/** 搜索 */
const handleSearch = () => {
  searchParams.value.page = 1;
  handleListPage();
};

/** 重置 */
const resetSearch = () => {
  resetSearchParams();
  handleListPage();
};

/** @current-change：点击分页组件页码发生变化：例如：切换第2、3页 OR 上一页 AND 下一页 OR 跳转某一页 */
/** @size-change：点击分页组件下拉选择条数发生变化：例如：选择10条/页、20条/页等 */
// 分页查询，@current-change AND @size-change都会触发分页，调用后端分页接口
/** 数据表格 */
const handleListPage = async () => {
  try {
    loading.value = true;
    tableList.value = []; // 重置表格数据
    const res: any = await listPage(searchParams.value);
    tableList.value = res.data.list;
    total.value = res.data.total;
    loading.value = false;
  } catch (error) {
    AppMsgWarning("数据查询失败，请刷新重试");
  }
};

/** 数据表格[删除、批量删除等刷新使用] */
const handleTableData = async () => {
  try {
    const res: any = await listPage(searchParams.value);
    tableList.value = res.data.list;
    total.value = res.data.total;
  } catch (error) {
    AppMsgWarning("数据查询失败，请刷新重试");
  }
};

// 静态页面防止报错(可直接删除)
// @ts-ignore
const handleStaticPage = () => {
  listPage(searchParams.value);
};

onMounted(() => {
  // 获取表格数据
  handleListPage();
});

const ids = ref([]); // 选择数组
const single = ref<boolean>(true); // 非单个禁用
const multiple = ref<boolean>(true); // 非多个禁用

/** 是否多选 */
const handleSelectionChange = (selection: any) => {
  // console.log(selection);
  ids.value = selection.map((item: any) => item.dictId);
  single.value = selection.length != 1; // 单选
  multiple.value = !selection.length; // 多选
};

/** 添加 */
const handleAdd = () => {
  // 打开抽屉
  AppDrawerRef.value.AppOpen();
  // 重置表单
  resetForm();
  // 标题
  title.value = "参数添加";
  form.value.status = "1";
};

/** 回显数据 */
const handleEcho = async (id: any) => {
  if (id == null || id == "") {
    AppMsgWarning("请选择需要修改的数据");
    return;
  }
  try {
    const res: any = await getById(id);
    form.value = res.data;
  } catch (error) {
    AppMsgWarning("数据获取失败，请刷新重试");
    console.log(error);
  }
};

/** 修改 */
const handleUpdate = async (row?: any) => {
  // 打开抽屉
  AppDrawerRef.value.AppOpen();
  // 重置表单
  resetForm();
  // 标题
  title.value = "参数修改";
  const id = row ? row.id : ids.value[0];
  if (id == null || id == "") {
    AppMsgError("请选择需要修改的数据");
  }
  console.log(id);
  // 回显数据
  handleEcho(id);
};

// 添加 OR 修改抽屉Ref
const AppDrawerRef = ref();
// 标题
const title = ref("系统参数管理");
// form表单Ref
const formRef = ref<any>();
// form表单
let form = ref<any>({
  id: "",
  sys_name: "",
  sys_explain: "",
  sys_value: "",
  sys_type: "",
  status: ""
});

/** 清空表单数据 */
const resetForm = () => {
  // 等待 DOM 更新完成
  nextTick(() => {
    if (formRef.value) {
      // 重置该表单项，将其值重置为初始值，并移除校验结果
      formRef.value.resetFields();
    }
  });    
  form.value = {
    id: "",
    sys_name: "",
    sys_explain: "",
    sys_type: "",
    status: "",
    sys_value: ""
  };
};

/** 表单规则 */
const rules = reactive({
  sys_name: [{ required: true, message: "请输入参数名称", trigger: "blur" }],
  sys_type: [{ required: true, message: "请输入参数类型", trigger: "blur" }],
  status: [{ required: true, message: "请选择参数状态", trigger: "blur" }]
});

// 确定按钮是否显示Loading
const confirmLoading = ref(false);

/** 确定  */
const handleConfirm = () => {
  if (!formRef.value) return;
  confirmLoading.value = true;
  (formRef.value as any).validate(async (valid: any) => {
    if (valid) {
      if (form.value.id != null && form.value.id != "") {
        try {
          await update(form.value.id,form.value);
          AppNoticeSuccess("修改成功");
          confirmLoading.value = false;
          AppDrawerRef.value.AppQuickClose();
          resetForm();
          handleListPage();
        } catch (error) {
          confirmLoading.value = false;
          AppNoticeError("修改失败，请刷新重试");
        }
      } else {
        try {
          await add(form.value);
          AppNoticeSuccess("添加成功");
          confirmLoading.value = false;
          AppDrawerRef.value.AppQuickClose();
          resetForm();
          handleListPage();
        } catch (error) {
          console.log(error);
          confirmLoading.value = false;
          AppNoticeError("添加失败，请刷新重试");
        }
      }
    } else {
      AppMsgError("验证失败，请检查填写内容");
      confirmLoading.value = false;
    }
  });
};

/** 取消 */
const handleCancel = () => {
  AppDrawerRef.value.AppClose();
};

/** 状态开关 */
const handleSwitch = (row: any, val: string) => {
  // 如果新值和原值相同，说明是初始化触发，直接返回
  if (val === row.status) return;
  
  let text = val === "1" ? "启用" : "停用";
  AppMsgBox("确认要[" + text + "]-[" + row.sys_name + "]吗？")
    .then(async () => {
      if (!row.id) {
        AppNoticeError("请选择需要修改的数据");
        return;
      }
      try {
        await updateStatus(row.id, val);
        AppNoticeSuccess("修改成功");
        row.status = val; // 更新成功后再更新本地状态
      } catch (error) {
        console.log(error);
        row.status = val === "1" ? "2" : "1"; // 失败时恢复原状态
        handleTableData();
        AppNoticeError("修改失败，请刷新重试");
      }
    })
    .catch(() => {
      row.status = val === "1" ? "2" : "1"; // 取消时恢复原状态
      AppMsgError("已取消");
    });
};

/** 删除 */
const handleDelete = (row: any) => {
  const id = row.id;
  if (id == null || id == "") {
    AppNoticeError("请选择需要删除的数据");
    return;
  }
  AppMsgBox("您确认需要删除参数名称[" + row.sys_name + "]么？")
    .then(async () => {
      try {
        await deleteById(id);
        handleTableData();
        AppNoticeSuccess("删除成功");
      } catch (error) {
        console.log(error);
        handleTableData();
        AppNoticeError("删除失败，请刷新重试");
      }
    })
    .catch(() => {
      AppMsgError("已取消");
    });
};


</script>

<style lang="scss" scoped></style>
